<template>
  <Header
    :title="{ zh: '原材料仓目视管理看板', en: 'Raw Material Warehouse Visual Board', index: 1 }"
  />

  <div class="EchartsContainer">
    <div class="row">
      <div class="item" style="width: 45%">
        <div class="title">当日出入库</div>
        <div class="echarts" id="main"></div>
      </div>
      <div class="item">
        <div class="title">月出入库</div>
        <div class="echarts" id="main2"></div>
      </div>
      <div class="item" style="width: 40%">
        <div class="title">月出入库存状况</div>
        <div class="echarts" id="main3"></div>
      </div>
    </div>

    <div class="row" style="margin-top: 10px">
      <div class="item" style="margin-right: 10px; width: 55%">
        <div class="title" style="text-align: start">入库明细</div>
        <el-table border ref="tab" class="table" :data="showData.tableData" style="height: 100%">
          <el-table-column align="center" prop="lotNo" label="指令号" />
          <el-table-column align="center" prop="custom" label="品牌" />
          <el-table-column align="center" prop="mtlName" label="材料名称" width="200" />
          <el-table-column align="center" prop="mtlUnit" label="单位" width="65" />
          <el-table-column align="center" prop="acceptQty" label="入库数" width="70" />
          <el-table-column align="center" prop="shortQty" label="欠数" width="65" />
          <el-table-column align="center" prop="recDate" label="入库日期" />
        </el-table>
      </div>
      <div class="item" style="width: 45%">
        <div class="title" style="text-align: start">库存明细</div>
        <el-table border class="table" ref="tab2" :data="showData.tableData2" style="height: 100%">
          <el-table-column align="center" prop="mtlName" label="材料名称" />
          <el-table-column align="center" prop="mtlUnit" label="单位" width="70" />
          <el-table-column align="center" prop="stkQty" label="库存数" width="70" />
          <el-table-column align="center" prop="lotNo" label="指令号" width="120" />
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
import Header from '../components/Header.vue'
import * as echarts from 'echarts'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import mtlApi from '@/api/material'

let rollTimer = ref() as any

const tab = ref<HTMLElement>() as any
const tab2 = ref<HTMLElement>() as any
const autoRoll = (stop: any) => {
  if (stop) {
    clearInterval(rollTimer.value)
    return
  }
  // 这里的 tab 是上方 table 表格绑定的ref值
  const divData = tab.value.layout.table.refs.bodyWrapper.firstElementChild.firstElementChild
  const divData2 = tab2.value.layout.table.refs.bodyWrapper.firstElementChild.firstElementChild
  rollTimer.value = setInterval(() => {
    // + 4 是每秒向下滑动 4个像素  这块可以自己更改
    divData.scrollTop += 1
    divData2.scrollTop += 1
    // console.log(divData.scrollTop)
    // 下方判断是滑动到底部就会自己回到最上方重新开始滑动  改动像素的话 一定要满足进入这个判断  否则滚动到底部就停了
    if (divData.clientHeight + divData.scrollTop == divData.scrollHeight) {
      divData.scrollTop = 0
    }
    if (divData2.clientHeight + divData2.scrollTop == divData2.scrollHeight) {
      divData2.scrollTop = 0
    }
  }, 150)
}
onMounted(() => {
  autoRoll(false)
})
onBeforeUnmount(() => {
  autoRoll(true)
})

const showData = ref({
  chart1: {
    data: []
  },
  chart2: {
    data: [
      {
        name: '星期一',
        type: 'bar',
        barGap: 0,
        label: {
          show: true,
          position: 'top'
        },
        emphasis: {
          focus: 'series'
        },
        data: []
      },
      {
        name: '星期二',
        type: 'bar',
        barGap: 0,
        label: {
          show: true,
          position: 'top'
        },
        emphasis: {
          focus: 'series'
        },
        data: []
      },
      {
        name: '星期三',
        type: 'bar',
        barGap: 0,
        label: {
          show: true,
          position: 'top'
        },
        emphasis: {
          focus: 'series'
        },
        data: []
      },
      {
        name: '星期四',
        type: 'bar',
        barGap: 0,
        label: {
          show: true,
          position: 'top'
        },
        emphasis: {
          focus: 'series'
        },
        data: []
      },
      {
        name: '星期五',
        type: 'bar',
        barGap: 0,
        label: {
          show: true,
          position: 'top'
        },
        emphasis: {
          focus: 'series'
        },
        data: []
      },
      {
        name: '星期六',
        type: 'bar',
        barGap: 0,
        label: {
          show: true,
          position: 'top'
        },
        emphasis: {
          focus: 'series'
        },
        data: []
      }
    ]
  },
  chart3: {
    xData: [],
    data: [],
    data2: []
  },
  tableData: [],
  tableData2: []
}) as any
const currentTime = () => {
  const date = new Date()
  const year = date!.getFullYear()
  const month = String(date!.getMonth() + 1).padStart(2, '0') // 使用padStart确保月份是两位数
  const day = String(date!.getDate()).padStart(2, '0') // 使用padStart确保日期是两位数
  // 返回格式化的日期时间字符串
  return `${year}-${month}-${day}`
}
const getData = async () => {
  // 获取日出入库查询
  try {
    let tableDataList = (await request.post('/show/mtl/io/status', {
      titleUnit: '日'
    })) as any
    tableDataList.forEach((item: any) => {
      showData.value.chart1.data.push(item.count)
    })
  } catch (error: any) {
    ElMessage.error(error)
  }
  // 获取当月出入库
  try {
    let tableDataList = (await request.post('/show/mtl/io/status', {
      // endDate: currentTime.value,
      pushUnit: 1,
      titleUnit: '当月'
    })) as any
    // 第一次插入出库，第二次插入入库
    showData.value.chart2.data.forEach((item: any) => {
      tableDataList.forEach((item2: any) => {
        if (item2.title === item.name && item2.type === 'O') {
          item.data.push(item2.count)
        }
      })
    })
    showData.value.chart2.data.forEach((item: any) => {
      tableDataList.forEach((item2: any) => {
        if (item2.title === item.name && item2.type === 'I') {
          item.data.push(item2.count)
        }
      })
    })
  } catch (error: any) {
    ElMessage.error(error)
  }

  // 获取月出入库
  try {
    let res = (await request.post('/show/mtl/io/status', {
      // endDate: currentTime.value,
      // pushUnit: 1,
      titleUnit: '月'
    })) as any
    showData.value.chart3.data.push(res[0].count)
    showData.value.chart3.data2.push(res[1].count)

    showData.value.chart3.xData.push(res[0].title)
  } catch (error: any) {
    ElMessage.error(error)
  }

  // 获取表格
  try {
    let tableDataList = (await request.post('/show/mtl/mtlIn/det', {
      brand: '',
      flag: '',
      lotNo: '',
      mtlName: '',
      pageNum: '',
      pageSize: '40'
    })) as any
    let tableDataList2 = (await request.post('/show/mtl/mtlStk/det', {
      brand: '',
      flag: '',
      lotNo: '',
      mtlName: '',
      pageNum: '',
      pageSize: '40'
    })) as any
    // let tableDataList2 = (await mtlApi.getMtlDetail()) as any
    showData.value.tableData = tableDataList.list
    showData.value.tableData2 = tableDataList2.list
  } catch (error: any) {
    ElMessage.error(error)
  }
}
const chartData = ref([
  {
    CtyQty: [
      1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
      27, 28, 29, 30, 31
    ],
    PreQty: [
      31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8,
      7, 6, 5, 4, 3, 2, 1
    ]
  }
]) as any
const MonthSendingAndReceiving = async () => {
  // 月 产能状况
  try {
    let qerM = (await request.post<any, any>(`/show/mtl/io/status`, {
      endDate: '',
      pushUnit: '',
      titleUnit: '当月'
    })) as any
    const cDMAP = new Map(
      qerM.map((item: any) => [item.type + item.title.split('/')[1], item.count])
    )
    chartData.value.forEach((item: any, index: number) => {
      item.CtyQty.forEach((item2: any, index2: number) => {
        if (cDMAP.get('I' + Number(index2 + 1))) {
          chartData.value[index].CtyQty[index2] = cDMAP.get('I' + Number(index2 + 1))
        } else {
          chartData.value[index].CtyQty[index2] = '0'
        }
      })
      item.PreQty.forEach((item2: any, index2: number) => {
        if (cDMAP.get('O' + Number(index2 + 1))) {
          chartData.value[index].PreQty[index2] = cDMAP.get('O' + Number(index2 + 1))
        } else {
          chartData.value[index].PreQty[index2] = '0'
        }
      })
    })
  } catch (error: any) {
    ElMessage.error(error)
  }
}

onMounted(async () => {
  // await getDeptTypes()
  await MonthSendingAndReceiving()
  await getData()
  getEchartsDom()
})
const getEchartsDom = () => {
  let chartDom = document.getElementById('main')
  let myChart = echarts.init(chartDom)
  let option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    grid: {
      left: 50,
      right: 30,
      top: 30,
      bottom: 40
    },
    xAxis: [
      {
        type: 'category',
        data: ['当日入库', '当日出库'],
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        min: 0,
        // interval: 40000,
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        type: 'bar',
        label: {
          show: true,
          position: 'top'
        },
        barWidth: '20%',
        tooltip: {
          valueFormatter: function (value: any) {
            return value
          }
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(
            0,
            0,
            0,
            1, // 渐变方向：从上到下
            [
              { offset: 0, color: '#88ADFB' },
              { offset: 1, color: '#E3ECFF' }
            ]
          )
        },
        data: showData.value.chart1.data
      }
    ]
  }
  option && myChart.setOption(option)

  // 第二张图
  let chartDom2 = document.getElementById('main2')
  let myChart2 = echarts.init(chartDom2)
  let option2 = {
    legend: {
      data: ['当月入库', '当月出库'],
      top: 'bottom'
    },
    grid: {
      left: 50,
      right: 20,
      top: 20,
      bottom: 50
    },
    xAxis: {
      type: 'category',
      data: [
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
        26, 27, 28, 29, 30, 31
      ]
    },
    yAxis: {
      type: 'value'
      //max: 12000
    },
    tooltip: {
      trigger: 'axis'
    },
    series: [
      {
        name: '当月入库',
        //data: [9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000],
        data: chartData.value[0].CtyQty,
        type: 'line',
        label: {
          show: true,
          position: 'top'
        },
        color: '#91CC75'
      },
      {
        name: '当月出库',
        //data: [0, 9882, 10231, 11350, 10825, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        data: chartData.value[0].PreQty,
        type: 'line',
        label: {
          show: true,
          position: 'top'
        },
        color: '#FAC858'
      }
    ]
  }
  option2 && myChart2.setOption(option2)

  // 第三张图
  let chartDom3 = document.getElementById('main3')
  let myChart3 = echarts.init(chartDom3)
  let option3 = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['入库', '出库'],
      top: 'bottom'
    },
    grid: {
      left: 50,
      right: 20,
      top: 30,
      bottom: 45
    },
    xAxis: [
      {
        type: 'category',
        data: showData.value.chart3.xData,
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        min: 0,
        // max: 100,
        // interval: 20,
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '入库',
        type: 'bar',
        barWidth: '20%',
        label: {
          show: true,
          position: 'top'
        },
        tooltip: {
          valueFormatter: function (value: any) {
            return value
          }
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(
            0,
            0,
            0,
            1, // 渐变方向：从上到下
            [
              { offset: 0, color: '#88ADFB' },
              { offset: 1, color: '#E3ECFF' }
            ]
          )
        },
        data: showData.value.chart3.data
      },
      {
        name: '出库',
        type: 'bar',
        barWidth: '20%',
        label: {
          show: true,
          position: 'top'
        },
        tooltip: {
          valueFormatter: function (value: any) {
            return value
          }
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(
            0,
            0,
            0,
            1, // 渐变方向：从上到下
            [
              { offset: 0, color: '#FF9940' },
              { offset: 1, color: '#FFFFFF' }
            ]
          )
        },
        data: showData.value.chart3.data2
      }
    ]
  }
  option3 && myChart3.setOption(option3)
}

onMounted(() => {
  function One() {
    if (location.href.indexOf('#reloaded') == -1) {
      location.href = location.href + '#reloaded'
      location.reload()
    }
  }
  One()
})
</script>

<style scoped lang="less">
.EchartsContainer {
  border-radius: 4px;
  margin-top: 10px;
  height: calc(100vh - 7vh - 40px);
  width: 100%;
}

.row {
  display: flex;
  height: 50%;
  width: 100%;

  .item {
    background-color: white;
    width: 100%;
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 0 10px 5px;

    // align-items: center;
    .title {
      font-weight: 900;
      font-size: 1rem;
      margin-top: 10px;
      text-align: center;
      color: black;
    }

    .echarts {
      flex: 1;
    }
  }
}

.table {
  margin-top: 5px;
}

:deep(thead) {
  .is-center {
    color: white;
    background-color: #ff9940;
  }
}
</style>
